package com.iuie.ns.datum.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iuie.ns.datum.service.IBlogService;
import com.iuie.ns.datum.service.IBlogSolrService;
import com.iuie.ns.datum.service.IFileInfoService;
import com.iuie.ns.datum.service.IFileService;
import com.iuie.ns.datum.service.IMsgService;
import com.iuie.ns.datum.vo.BlogInfoVO;
import com.iuie.ns.datum.vo.BlogReadRecordVO;
import com.iuie.ns.datum.vo.FileInfoVO;
import com.iuie.ns.datum.vo.PlatformMsgVO;
import com.iuie.ns.frame.utils.DateUtils;
import com.iuie.ns.frame.utils.MarkdownUtils;
import com.iuie.ns.frame.utils.ShiroUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.frame.web.response.vo.ResponseInfo;
import com.iuie.ns.system.service.code.ISysCodeInfoService;
import com.iuie.ns.system.vo.code.SysCodeInfoVO;
import com.iuie.ns.system.vo.user.SysUserVO;

/**
 * @desc 博客模块控制器
 * @createTime 2017年8月19日 下午3:55:16
 * @author iuie
 */
@RequestMapping("datum/blog")
@Controller
public class BlogController {
	
	private static final Logger logger = LoggerFactory.getLogger(BlogController.class);
	
	@Autowired
	private ISysCodeInfoService sysCodeInfoService;
	
	@Autowired
	private IBlogService blogService;
	
	@Autowired
	private IFileInfoService fileInfoService;
	
	@Autowired
	private IBlogSolrService blogSolrService;
	
	@Resource
	private IFileService fileService;
	
	@Resource
	private IMsgService msgService;

	/**
	 * 列表结构博客分类--博客页面
	 * @param request
	 * @return
	 * @date 2017年8月22日 上午8:43:57
	 */
	@RequestMapping
	public String index(HttpServletRequest request){
		List<SysCodeInfoVO> blogTypes = sysCodeInfoService.findByCodeTypeId("blogType", 1);
		request.setAttribute("blogTypes", blogTypes); // 查询出blogTypes
		return "view-datum/blog/blog";
	}
	
	/**
	 * 树形结构博客分类-博客页面
	 * @param request
	 * @return
	 * @date 2017年8月22日 上午8:45:04
	 */
	@RequestMapping("treeBlog/index")
	public String blogTreeIndex(HttpServletRequest request) {
		List<SysCodeInfoVO> blogTypes = sysCodeInfoService.findByCodeTypeId("blogType", 1);
		request.setAttribute("blogTypes", blogTypes); // 查询出blogTypes
		return "view-datum/blog/treeBlog";
	}
	
	/**
	 * 新增博客页面
	 * @param blogType
	 * @param request
	 * @return
	 */
	@RequestMapping("blogAdd/index/{blogType}")
	public String blogAddIndex(@PathVariable("blogType") String blogType, HttpServletRequest request) {
		request.setAttribute("blogType", blogType);
		return "view-datum/blog/blogAdd";
	}
	
	/**
	 * 修改博客页面
	 * @param blogId
	 * @param request
	 * @return
	 */
	@RequestMapping("blogUpdate/index/{blogId}")
	public String blogUpdateIndex(@PathVariable("blogId") String blogId, HttpServletRequest request) {
		// 文件或超链接形式
		request.setAttribute("blogId", blogId);
		return "view-datum/blog/blogUpdate";
	}
	
	/**
	 * markdown形式修改博客页面
	 * @param blogId
	 * @param request
	 * @return
	 */
	@RequestMapping("mdBlogUpdate/index/{blogId}")
	public String mdBlogUpdateIndex(@PathVariable("blogId") String blogId, HttpServletRequest request) {
		// markdown形式 博客编辑页
		BlogInfoVO blogInfo = blogService.findById(Long.valueOf(blogId));
		SysCodeInfoVO blogType = sysCodeInfoService.findCodeInfoByCodeValueAndCodeType(blogInfo.getBlogType().getCodeInfoValue(), "blogType");
		request.setAttribute("blogTypeName", blogType.getCodeInfoName());
		request.setAttribute("blogTypeId", blogType.getCodeInfoValue());
		request.setAttribute("blogId", blogId);
		return "view-datum/blog/mdBlogEdit";
	}
	
	/**
	 * 列表结构博客-博客类型编辑页
	 * @return
	 */
	@RequestMapping("editBlogType/index")
	public String blogTypeEditIndex() {
	    return "view-datum/blog/editBlogType";
	}
	
	/**
	 * 更改博客类型
	 * @return
	 */
	@RequestMapping("switchBlogType/{from}/index")
	public String switchBlogTypeIndex(@PathVariable("from") String from, HttpServletRequest request) {
		request.setAttribute("from", from);
		return "view-datum/blog/switchBlogType";
	}
	
	@RequestMapping("switchBlogBook/{from}/{blogId}/index")
	public String switchBlogBook(@PathVariable("from") String from,@PathVariable("blogId") String blogId, HttpServletRequest request){
		request.setAttribute("from", from);
		request.setAttribute("blogId", blogId);
		return "view-datum/blog/switchBlogBook";
	}
	
	/**
	 * 树形结构博客-类型编辑页
	 * @return
	 */
	@RequestMapping("editTreeBlogType/index")
	public String treeBlogTypeEditIndex() {
	    return "view-datum/blog/editTreeBlogType";
	}
	
	/**
	 * markdown编辑页
	 * @param blogType
	 * @param request
	 * @return
	 */
	@RequestMapping("mdBlogEdit/{blogType}/index")
	public String mdBlogEditIndex(@PathVariable("blogType") String blogTypeId, HttpServletRequest request) {
		SysCodeInfoVO blogType = sysCodeInfoService.findCodeInfoByCodeValueAndCodeType(blogTypeId, "blogType");
		request.setAttribute("blogTypeName", blogType.getCodeInfoName());
		request.setAttribute("blogTypeId", blogType.getCodeInfoValue());
		return "view-datum/blog/mdBlogEdit";
	}
	
	@RequestMapping("viewBlog/{blogId}/index")
	public String viewBlog(@PathVariable("blogId") Long blogId, HttpServletRequest request) {
		BlogInfoVO blogInfo = blogService.findById(blogId);
		request.setAttribute("blogInfo", blogInfo);
		return "view-datum/blog/viewBlog";
	}
	
	/**
	 * 打开打包markdown的页面
	 * @return
	 */
	@RequestMapping("mdPack/index")
	public String mdPackIndex() {
		return "view-datum/blog/mdPack";
	}
	
	/**
	 * 添加博客概述的页面
	 * @param remarks
	 * @return
	 * @date 2018年5月6日下午4:01:05
	 */
	@RequestMapping("desc/edit/{remarks}/index")
	public String mdBlogDescAddIndex(@PathVariable("remarks") String remarks, HttpServletRequest request) {
		String codeRemarks = null;
		if (StringUtils.equals(remarks, "-")) {
			codeRemarks = "";
		} else {
			codeRemarks = remarks;
		}
		request.setAttribute("codeRemarks", codeRemarks);
		return "view-datum/blog/mdBlogAddDesc";
	}
	
	/**
	 * 博客报表index页面
	 * @return
	 * @date 2018年5月26日下午1:37:57
	 */
	@RequestMapping("report")
	public String index() {
		return "view-datum/blogReport/blogReport";
	}
	
	/**
	 * 根据blog type查询博客
	 * @param type 博客类型
	 * @return
	 */
	@RequestMapping(value="article/{type}")
	@ResponseBody
	public ResponseInfo findBlogByBlogType(@PathVariable("type") String type){
		if (StringUtils.isBlank(type)) {
			return ResponseInfo.errorInfo("错误：查询参数为空!");
		}
		List<BlogInfoVO> list = blogService.findByBlogType(type);
		return ResponseInfo.successInfo(list);
	}
	
	/**
	 * 根据blog id 查询博客
	 * @param blogId 博客id
	 * @return
	 */
	@RequestMapping(value="findById/{blogId}")
	@ResponseBody
	public ResponseInfo findById(@PathVariable("blogId") String blogId){
		if (StringUtils.isBlank(blogId)) {
			return ResponseInfo.errorInfo("查询参数为空");
		}
		Long id = Long.valueOf(blogId);
		BlogInfoVO blogInfo = blogService.findById(id);
		return ResponseInfo.successInfo(blogInfo);
	}
	
	/**
	 * 根据blog Id删除博客
	 */
	@RequestMapping(value="delete/{blogId}")
	@ResponseBody
	public ResponseInfo deleteBlog(@PathVariable("blogId") Long blogId){
		blogService.deleteById(blogId);
		return ResponseInfo.successInfo("博客删除成功！");
	}
	
	/**
	 * 标记阅读
	 * @param blogId
	 * @return
	 */
	@RequestMapping(value="signRead/{blogId}")
	@ResponseBody
	public ResponseInfo signRead(@PathVariable("blogId") Long blogId){
		blogService.updateBySignRead(blogId);
		return ResponseInfo.successInfo(blogId);
	}
	
	/**
	 * 新增博客
	 * @param blogInfo
	 * @return
	 * @throws IOException
	 * @date 2017年8月30日 上午9:51:23
	 */
	@RequestMapping(value="addBlog")
	@ResponseBody
	public ResponseInfo addOne(BlogInfoVO blogInfo) throws Exception{
		BlogInfoVO mInfo = blogService.addBlog(blogInfo);
		logger.info("新增博客成功：{}",mInfo);
		return ResponseInfo.successInfo("博客保存成功！");
	}
	
	/**
	 * 新增博客，markdown形式新增
	 * @param blogInfo
	 * @param htmlContent
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="mdAddBlog")
	@ResponseBody
	public ResponseInfo mdAddBlog(BlogInfoVO blogInfo) throws Exception{
		String htmlContent = MarkdownUtils.toHtml(blogInfo.getBlogName(), blogInfo.getMdContent());
		FileInfoVO fileInfo = fileService.newFileWithContent(htmlContent, "blog", blogInfo.getBlogName() + ".html");
		BlogInfoVO mInfo = blogService.addMdBlog(blogInfo, fileInfo);
		logger.info("新增博客成功：{}",mInfo);
		return ResponseInfo.successInfo("博客保存成功！", mInfo.getBlogId());
	}
	
	/**
	 * 修改博客，markdown形式修改
	 * @param blogInfo
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="mdUpdateBlog")
	@ResponseBody
	public ResponseInfo mdUpdateBlog(BlogInfoVO blogInfo) throws IOException {
		String htmlContent = MarkdownUtils.toHtml(blogInfo.getBlogName(), blogInfo.getMdContent());
		fileService.updateFileWithContent(blogInfo.getFileInfo().getFileId(), htmlContent, "blog", blogInfo.getBlogName() + ".html");
		blogService.updateMdBlog(blogInfo);
		return ResponseInfo.successInfo("博客保存成功！");
	}
	
	/**
	 * 提供一个空的搜索
	 * @return
	 */
	@RequestMapping(value="search")
	@ResponseBody
	public ResponseInfo serach() {
		return ResponseInfo.successInfo(new ArrayList<>());
	}
	
	/**
	 * solr搜索博客
	 * @param searchKey
	 * @return
	 * @throws SolrServerException
	 * @throws IOException
	 */
	@RequestMapping(value="search/{searchKey}")
	@ResponseBody
	public ResponseInfo serach(@PathVariable("searchKey") String searchKey) throws SolrServerException, IOException{
		List<BlogInfoVO> mInfoList = blogSolrService.findByContextOrName("MD_CONTENT",searchKey);
		logger.info("查询博客成功:{}",mInfoList);
		return ResponseInfo.successInfo("查询博客成功", mInfoList);
	}
	
	/**
	 * 下载markdown类型博客的markdown文档
	 * @param blogId
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/mdDownload/{blogId}",method=RequestMethod.GET)
    public void mdDownload(@PathVariable("blogId") String blogId, HttpServletResponse resp) throws IOException{
        blogService.mdDownload(blogId, resp);
    }
	
	/**
	 * 查询markdown类型的博客
	 * @param platformMsg
	 * @param page
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value="find/latestMdBlog")
	@ResponseBody
	public ResponseInfo findLatestMdBlog(PlatformMsgVO platformMsg, Page page) throws ParseException {
		SysUserVO user = (SysUserVO) ShiroUtils.getCurrentUser();
		platformMsg.setCreatorId(user.getUserId());
		List<PlatformMsgVO> list = msgService.findLatestMsg(platformMsg, page, "1");
		return ResponseInfo.successInfo(list, page);
	}
	
	/**
	 * 打包markdown博客
	 * @param startTime
	 * @param endTime
	 * @param expects 排除在外的博客
	 * @throws IOException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="mdPack", method=RequestMethod.POST)
	public void mdPack(String startTime, String endTime, String[] expects, HttpServletResponse response) throws IOException, ParseException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/octet-stream");
		String fileName = "Markdown-" + DateUtils.getLooseCurrentDateTime() + ".zip";
		response.setHeader("Content-Disposition", "form-data; name=\"attachment\";filename=\"" + fileName + "\"");
		blogService.mdPack(startTime, endTime, expects, response.getOutputStream());
	}
	
	/**
	 * 查看blog的阅读历史记录
	 * @param blogId
	 */
	@RequestMapping(value = "read/find/index/{blogId}")
	public String findReadBolgPersons(@PathVariable("blogId") String blogId,
			HttpServletRequest request) {
		request.setAttribute("blogId", blogId);
		return "view-datum/blog/blogRead";
	}

	/**
	 * 分页查询个人阅读的书籍
	 * @param page
	 * @param blogId
	 * @return
	 * @date 2018年5月6日下午4:09:39
	 */
	@RequestMapping(value = "read/find/page/{blogId}")
	@ResponseBody
	public ResponseInfo findReadBolgPersonsByPage(Page page, @PathVariable("blogId") String blogId) {
		List<BlogReadRecordVO> blogReadList = new ArrayList<BlogReadRecordVO>();
		if (StringUtils.isNotBlank(blogId)) {
			Long id = Long.valueOf(blogId);
			blogReadList = blogService.findBlogReadbyIdPage(page, id);
		}
		return ResponseInfo.successInfo(blogReadList, page);
	}
	
	/**
	 * 
	 * @param blogId
	 * @param request
	 * @return
	 * @date 2018年5月6日下午4:10:20
	 */
	@RequestMapping("desc/add/{blogId}")
	@ResponseBody
	public ResponseInfo mdBlogDescAdd(@PathVariable("blogId") Long blogId, HttpServletRequest request, String remarks) {
		blogService.updateMdBlogRemark(blogId, remarks);
		return ResponseInfo.successInfo("保存博客概述成功！");
	}
	
	/**
	 * 
	 * @param blogId
	 * @return
	 * @date 2018年5月7日上午8:59:08
	 */
	@RequestMapping("find/desc/{blogId}")
	@ResponseBody
	public ResponseInfo findRemarkById(@PathVariable("blogId") Long blogId) {
		String remark = blogService.findRemarkById(blogId);
		return ResponseInfo.successInfoByObject(remark);
	}
}
